package com.baseweb.webadmin.core.util;

import com.baseweb.webadmin.core.model.pojo.ByChannel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by dengsy on 2017-06-25.
 */
public class TreeBuilder {
    List<ByChannel> nodes = new ArrayList<>();

    public TreeBuilder() {

    }

    public TreeBuilder(List<ByChannel> nodes) {
        super();
        this.nodes = nodes;
    }

    public List<ByChannel> buildTree(List<ByChannel> nodes) {

        TreeBuilder treeBuilder = new TreeBuilder(nodes);

        return treeBuilder.buildTree();
    }

    // 构建树形结构
    public List<ByChannel> buildTree() {
        List<ByChannel> treeNodes = new ArrayList<>();
        List<ByChannel> rootNodes = getRootNodes();
        for (ByChannel rootNode : rootNodes) {
            buildChildNodes(rootNode);
            treeNodes.add(rootNode);
        }
        Collections.sort(treeNodes);
        return treeNodes;
    }

    // 递归子节点
    public void buildChildNodes(ByChannel node) {
        List<ByChannel> children = getChildNodes(node);
        if (!children.isEmpty()) {
            for (ByChannel child : children) {
                buildChildNodes(child);
            }
            Collections.sort(children);
            node.setChannelList(children);
        }
    }

    // 获取父节点下所有的子节点
    public List<ByChannel> getChildNodes(ByChannel pnode) {
        List<ByChannel> childNodes = new ArrayList<>();
        for (ByChannel n : nodes) {
            if (pnode.getId().equals(n.getParentId())) {
                childNodes.add(n);
            }
        }
        return childNodes;
    }

    // 判断是否为根节点
    public boolean rootNode(ByChannel node) {
        boolean isRootNode = true;
        for (ByChannel n : nodes) {
            if (node.getParentId().equals(n.getId())) {
                isRootNode = false;
                break;
            }
        }
        return isRootNode;
    }

    // 获取集合中所有的根节点
    public List<ByChannel> getRootNodes() {
        List<ByChannel> rootNodes = new ArrayList<>();
        for (ByChannel n : nodes) {
            if (rootNode(n)) {
                rootNodes.add(n);
            }
        }
        Collections.sort(rootNodes);
        return rootNodes;
    }
}
